package com.studydemo.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.HashMap;

/**
 * 全局异常处理
 * */
@ControllerAdvice(annotations = {RestController.class, Controller.class})  //只要类上加了这两个处理器的就会被拦截
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 进行异常处理 SQLIntegrityConstraintViolationException
     * */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        //判断异常信息里面是否含有该关键字，做进一步处理
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");  //以空格分割
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误！");
    }

    /**
     * 自定义处理异常
     * @param ex
     * @return
     */
    @ExceptionHandler({ RuntimeException.class})
    public R handleOtherExceptions(RuntimeException ex){
        String message = ex.getMessage();
        return R.error(ex.getMessage());
    }
}
